const Order = require('../model/Order');
const Product = require('../model/Product');

// 获取订单列表
exports.getOrders = async (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 10, 
            status, 
            paymentStatus, 
            deliveryStatus,
            keyword,
            startDate,
            endDate
        } = req.query;

        // 构建查询条件
        const filter = {};
        
        if (status) filter.status = status;
        if (paymentStatus) filter.paymentStatus = paymentStatus;
        if (deliveryStatus) filter.deliveryStatus = deliveryStatus;
        
        // 关键词搜索（订单号或客户姓名）
        if (keyword) {
            filter.$or = [
                { orderNumber: { $regex: keyword, $options: 'i' } },
                { 'customer.name': { $regex: keyword, $options: 'i' } },
                { 'customer.phone': { $regex: keyword, $options: 'i' } }
            ];
        }
        
        // 时间范围查询
        if (startDate || endDate) {
            filter.orderTime = {};
            if (startDate) filter.orderTime.$gte = new Date(startDate);
            if (endDate) filter.orderTime.$lte = new Date(endDate + ' 23:59:59');
        }

        const skip = (page - 1) * limit;
        
        const orders = await Order.find(filter)
            .populate('items.productId', 'name image')
            .sort({ orderTime: -1 })
            .skip(skip)
            .limit(parseInt(limit));

        const total = await Order.countDocuments(filter);

        res.json({
            code: 0,
            message: '获取订单列表成功',
            data: {
                orders,
                pagination: {
                    current: parseInt(page),
                    pageSize: parseInt(limit),
                    total,
                    pages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        console.error('获取订单列表错误:', error);
        res.json({
            code: 1,
            message: '获取订单列表失败',
            error: error.message
        });
    }
};

// 获取订单详情
exports.getOrderDetail = async (req, res) => {
    try {
        const { id } = req.params;
        
        const order = await Order.findById(id)
            .populate('items.productId', 'name image category brand');
        
        if (!order) {
            return res.json({
                code: 1,
                message: '订单不存在'
            });
        }

        res.json({
            code: 0,
            message: '获取订单详情成功',
            data: order
        });
    } catch (error) {
        console.error('获取订单详情错误:', error);
        res.json({
            code: 1,
            message: '获取订单详情失败',
            error: error.message
        });
    }
};

// 创建订单
exports.createOrder = async (req, res) => {
    try {
        const { customer, items, deliveryFee = 0, discountAmount = 0, paymentMethod, remark } = req.body;

        // 验证商品并计算金额
        let totalAmount = 0;
        const orderItems = [];

        for (const item of items) {
            const product = await Product.findById(item.productId);
            if (!product) {
                return res.json({
                    code: 1,
                    message: `商品不存在: ${item.productId}`
                });
            }

            if (product.stock < item.quantity) {
                return res.json({
                    code: 1,
                    message: `商品库存不足: ${product.name}`
                });
            }

            const subtotal = product.price * item.quantity;
            totalAmount += subtotal;

            orderItems.push({
                productId: item.productId,
                productName: product.name,
                price: product.price,
                quantity: item.quantity,
                subtotal
            });
        }

        const actualAmount = totalAmount + deliveryFee - discountAmount;

        const order = new Order({
            customer,
            items: orderItems,
            totalAmount,
            deliveryFee,
            discountAmount,
            actualAmount,
            paymentMethod,
            remark
        });

        await order.save();

        // 更新商品库存
        for (const item of items) {
            await Product.findByIdAndUpdate(
                item.productId,
                { $inc: { stock: -item.quantity } }
            );
        }

        res.json({
            code: 0,
            message: '创建订单成功',
            data: order
        });
    } catch (error) {
        console.error('创建订单错误:', error);
        res.json({
            code: 1,
            message: '创建订单失败',
            error: error.message
        });
    }
};

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
    try {
        const { id } = req.params;
        const { status, paymentStatus, deliveryStatus } = req.body;

        const updateData = {};
        if (status) updateData.status = status;
        if (paymentStatus) updateData.paymentStatus = paymentStatus;
        if (deliveryStatus) updateData.deliveryStatus = deliveryStatus;

        // 根据状态更新时间戳
        if (paymentStatus === '已支付' && !updateData.paymentTime) {
            updateData.paymentTime = new Date();
        }
        if (deliveryStatus === '配送中' && !updateData.shipmentTime) {
            updateData.shipmentTime = new Date();
        }
        if (status === '已完成' && !updateData.completionTime) {
            updateData.completionTime = new Date();
        }

        const order = await Order.findByIdAndUpdate(
            id,
            updateData,
            { new: true }
        );

        if (!order) {
            return res.json({
                code: 1,
                message: '订单不存在'
            });
        }

        res.json({
            code: 0,
            message: '更新订单状态成功',
            data: order
        });
    } catch (error) {
        console.error('更新订单状态错误:', error);
        res.json({
            code: 1,
            message: '更新订单状态失败',
            error: error.message
        });
    }
};

// 删除订单
exports.deleteOrder = async (req, res) => {
    try {
        const { id } = req.params;

        const order = await Order.findById(id);
        if (!order) {
            return res.json({
                code: 1,
                message: '订单不存在'
            });
        }

        // 只允许删除已取消的订单
        if (order.status !== '已取消') {
            return res.json({
                code: 1,
                message: '只能删除已取消的订单'
            });
        }

        await Order.findByIdAndDelete(id);

        res.json({
            code: 0,
            message: '删除订单成功'
        });
    } catch (error) {
        console.error('删除订单错误:', error);
        res.json({
            code: 1,
            message: '删除订单失败',
            error: error.message
        });
    }
};

// 批量删除订单
exports.batchDeleteOrders = async (req, res) => {
    try {
        const { ids } = req.body;

        if (!ids || !Array.isArray(ids)) {
            return res.json({
                code: 1,
                message: 'ids参数错误，应为数组格式'
            });
        }

        // 检查所有订单都是已取消状态
        const orders = await Order.find({ _id: { $in: ids } });
        const nonCancelledOrders = orders.filter(order => order.status !== '已取消');
        
        if (nonCancelledOrders.length > 0) {
            return res.json({
                code: 1,
                message: '只能删除已取消的订单'
            });
        }

        await Order.deleteMany({ _id: { $in: ids } });

        res.json({
            code: 0,
            message: `成功删除${ids.length}个订单`
        });
    } catch (error) {
        console.error('批量删除订单错误:', error);
        res.json({
            code: 1,
            message: '批量删除订单失败',
            error: error.message
        });
    }
};

// 获取订单统计信息
exports.getOrderStats = async (req, res) => {
    try {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);

        // 今日订单统计
        const todayStats = await Order.aggregate([
            {
                $match: {
                    orderTime: { $gte: today, $lt: tomorrow }
                }
            },
            {
                $group: {
                    _id: null,
                    totalOrders: { $sum: 1 },
                    totalAmount: { $sum: '$actualAmount' },
                    paidOrders: {
                        $sum: {
                            $cond: [{ $eq: ['$paymentStatus', '已支付'] }, 1, 0]
                        }
                    },
                    paidAmount: {
                        $sum: {
                            $cond: [{ $eq: ['$paymentStatus', '已支付'] }, '$actualAmount', 0]
                        }
                    }
                }
            }
        ]);

        // 订单状态统计
        const statusStats = await Order.aggregate([
            {
                $group: {
                    _id: '$status',
                    count: { $sum: 1 }
                }
            }
        ]);

        res.json({
            code: 0,
            message: '获取订单统计成功',
            data: {
                today: todayStats[0] || { totalOrders: 0, totalAmount: 0, paidOrders: 0, paidAmount: 0 },
                statusStats
            }
        });
    } catch (error) {
        console.error('获取订单统计错误:', error);
        res.json({
            code: 1,
            message: '获取订单统计失败',
            error: error.message
        });
    }
}; 